<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/3
 * Time: 16:18
 */

namespace app\api\controller;

use app\api\model\ClassroomType as ClassroomTypeModel;//课程分类
use app\api\model\Classroom as ClassroomModel;//课程
use app\api\model\ClassroomCatalogue as ClassroomCatalogueModel;//课程章节
use app\api\model\ClassroomUser as ClassroomUserModel;//购买课程
use app\api\model\MyClassroom as MyClassroomModel;//我的收藏
use app\api\model\ClassroomComment as ClassroomCommentModel;//评论
use app\api\model\ClassroomHistory as ClassroomHistoryModel;//观看历史
use app\api\model\AboutUs as AboutUsModel;//关于我们
use think\Db;

class Classroom extends Common
{
    /**
     * 获取课程分类ID、名称
     */
    public function classroomType()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        
        $classroomTypeModel = new ClassroomTypeModel();
        $type = $classroomTypeModel->getClassroomType();
        return $this->apiSuccess($type);
    }
    
    /**
     * 课程列表
     * page：当前页码
     * classroomType：课程分类ID  默认为-1，表示全部
     * order：排序规则  默认为1    1综合  2最热  3最新  4价格
     * orderP：价格排序规则   当order值为4时，需要该参数，默认值为1   1价格升序  2价格降序
     */
    public function classroomLists()
    {
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $field = 'id, classroom_title, classroom_price, classroom_img, classroom_cate';
        $where = [];
        if($params['classroomType'] != -1) {
            $where ['classroom_id'] = $params['classroomType'];//课堂分类
        }
        if($params['order'] == 1) {//综合排序
            $order = 'classroom_sort desc';
        } elseif($params['order'] == 2) {//最热排序
            $order = 'classroom_playnum desc';
        } elseif($params['order'] == 3) {//最新排序
            $order = 'create_time desc';
        } elseif($params['order'] == 4) {//价格排序
            if($params['orderP'] == 1) {//价格升序
                $order = 'classroom_price, classroom_playnum desc';
            } elseif($params['orderP'] == 2) {//价格降序
                $order = 'classroom_price desc, classroom_playnum desc';
            }
        }
        $classroomModel = new ClassroomModel();
        $lists = $classroomModel->getClasssroomList($field, $where, $order, $params['page'], 10);
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        foreach($lists as &$list) {
            $num = $classroomCatalogue->countNum($list['id']);
            $list['num'] = $num;
        }
        return $this->apiSuccess($lists);
    }
    
    /**
     * 课程基本信息
     * classroom_cata：课程类型   1 免费课程  2 付费课程
     * classroom_id：课程ID
     */
    public function classroomInfo()
    {
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] != 0){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == false) {
                return $this->apiError(301);
            }
        }
        $aboutUsModel = new AboutUsModel();
        $field = 'price_button';
        $price_button = $aboutUsModel->getField($field);
        if($price_button['price_button'] == 1){//如果价格不隐藏，则判断课程是否是付费课程
            $classroom_cate = Db::table('up_classroom')->where('id', $params['classroom_id'])->value('classroom_cate');
            if($classroom_cate == 2) {//如果是付费课程，判断该用户有没有购买
                $classroomuserModel = new ClassroomUserModel();
                $res = $classroomuserModel->ifBuy($params['classroom_id'], $params['user_id']);
                if(! $res){
                    return $this->apiError(4003);
                }
            }
        }
        
        $classroomModel = new ClassroomModel();
        $classroomModel->playSort($params['classroom_id']);//播放量加1&排序加2
        $field = 'id, classroom_playnum, classroom_title, classroom_price';
        $classroomInfo = $classroomModel->getClassroomInfo($field, $params['classroom_id']);
        //是否收藏
        $collection = 1;//已收藏
        $myClassroomModel = new MyClassroomModel();
        $result = $myClassroomModel->ifCollection($params['classroom_id'], $params['user_id']);
        if(!$result){
            $collection = 2;//未收藏
        }
        $classroomInfo['collection'] = $collection;
        return $this->apiSuccess($classroomInfo);
    }
    
    /**
     * 课程的详细信息
     * classroom_id：课程ID
     */
    public function classroomDetail(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] != 0){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == false) {
                return $this->apiError(301);
            }
        }
        $field = 'classroom_content';
        $classroomModel = new ClassroomModel();
        $classroomDetail = $classroomModel->getClassroomInfo($field, $params['classroom_id']);
        return $this->apiSuccess($classroomDetail);
    }
    
    /**
     * 课程目录
     * @return string
     * classroom_id：课程ID
     */
    public function catalogue(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] != 0){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == false) {
                return $this->apiError(301);
            }
        }
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        $num = $classroomCatalogue->countNum($params['classroom_id']);
        //目录
        $field = 'catalogue_id, catalogue_img, catalogue_url, catalogue_title, catalogue_time';
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        $list = $classroomCatalogueModel->catalogueLists($field, $params['classroom_id']);
        return json_encode(['status'=>200, 'msg'=>'成功', 'num'=>$num, 'data'=>$list], 256);
    }
    
    /**
     * 视频播放地址
     * classroom_id：课程ID
     * catalogue_id：目录ID
     */
    public function videoUrl(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] != 0){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == false) {
                return $this->apiError(301);
            }
        }
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        
        if($params['catalogue_id'] == ''){//首次进入页面时，默认显示第一节
            $url = $classroomCatalogueModel->getUrl($params['classroom_id']);
        }else{
            $field = 'catalogue_id, catalogue_url, catalogue_img, catalogue_title, catalogue_time';
            $url = $classroomCatalogueModel->getUrl('', $params['catalogue_id'], $field);
        }
        return $this->apiSuccess($url);
    }
    
    /**
     * 评论列表
     * page：当前页码
     * classroom_id：课程ID
     */
    public function classroomComment(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] != 0){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == false) {
                return $this->apiError(301);
            }
        }
        //该课程所有评论
        $pageNum = $params['page'] - 1;
        $field = 'c.comment_id, c.comment_content, c.comment_img, 
        c.create_time, c.classroom_id, c.like_num, uuu.user_username, uuu.user_image, uuu.user_id';
        $lists = Db::table('up_classroom_comment')->alias('c')
            ->field($field)
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('comment_type', 1)
            ->where('c.classroom_id', $params['classroom_id'])
            ->order('c.create_time desc')
            ->limit($pageNum * 10, 10)
            ->select();
        //评论下的所有回复
        $field1 = 'c.comment_id, c.comment_content, c.parent_id, c.classroom_id, 
        c.like_num, uuu.user_username, uuu.user_id';
        $classroomCommentModel = new ClassroomCommentModel();
        $replyLists = $classroomCommentModel->getReplyLists($field1, $params['classroom_id']);
        //回复是否被该用户收藏
        foreach($replyLists as $key=>&$replyList){
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $params['user_id'])
                ->where('data_id', $replyList['comment_id'])
                ->find();
            if($res){
                $replyList['like'] = 1;
            }else{
                $replyList['like'] = 2;
            }
        }
        //评论是否被该用户收藏
        foreach($lists as $k=>&$vo){
            if(!empty($vo['comment_img'])){
                $vo['comment_img'] = explode(',', $vo['comment_img']);
            }else{
                $vo['comment_img'] = [];
            }
            
            $res = Db::table('up_dz')
                ->where('type', 7)
                ->where('user_id', $params['user_id'])
                ->where('data_id', $vo['comment_id'])
                ->find();
            if($res){
                $vo['like'] = 1;
            }else{
                $vo['like'] = 2;
            }
        }
        //评论下的所有回复
        foreach($lists as $key=>&$list){
            $list['son'] = [];
            $list['sonNum'] = 0;
            for($i=0; $i<count($replyLists); $i++){
                if($list['comment_id'] == $replyLists[$i]['parent_id']){
                    $list['son'][] = $replyLists[$i];
                }
            }
            $list['sonNum'] = count($list['son']);//该评论下回复的数量
        }
        //所有评论数
        $num = Db::table('up_classroom_comment')
            ->where('comment_type', 1)
            ->where('classroom_id', $params['classroom_id'])
            ->count();
        return json_encode(['status'=>200, 'msg'=>'成功', 'num'=>$num, 'data'=>$lists], 256);
    }
    
    /**
     * 获取回复详情
     * comment_id：评论ID
     */
    public function commentDetail(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $field = 'c.comment_id, c.comment_content, c.comment_img, c.create_time, 
        c.classroom_id, c.like_num, uuu.user_username, uuu.user_image, uuu.user_id';
        //评论详情
        $oneComment = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.comment_id', $params['comment_id'])
            ->field($field)
            ->find();
        //单条评论下所有回复
        $replys = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.parent_id', $params['comment_id'])
            ->field($field)
            ->order('c.create_time desc')
            ->select();
        $sonNum = count($replys);//单条评论下的所有回复数量
        $oneComment['sonNum'] = $sonNum;
        //评论是否被该用户点赞
        $resC = Db::table('up_dz')
            ->where('type', 7)
            ->where('user_id', $params['user_id'])
            ->where('data_id', $oneComment['comment_id'])
            ->find();
        if($resC){
            $oneComment['like'] = 1;
        }else{
            $oneComment['like'] = 2;
        }
        //转换图片为数组
        if(!empty($oneComment['comment_img'])){
            $oneComment['comment_img'] = explode(',', $oneComment['comment_img']);
        }else{
            $oneComment['comment_img'] = [];
        }
        //回复是否被该用户点赞
        foreach($replys as $key=>&$reply){
            //转换图片为数组
            if(!empty($reply['comment_img'])){
                $reply['comment_img'] = explode(',', $reply['comment_img']);
            }else{
                $reply['comment_img'] = [];
            }
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $params['user_id'])
                ->where('data_id', $reply['comment_id'])
                ->find();
            if($res){
                $reply['like'] = 1;
            }else{
                $reply['like'] = 2;
            }
        }
        $oneComment['son'] = $replys;
        return $this->apiSuccess($oneComment);
    }
    
    /**
     * 写评论
     * content：发布的内容
     * classroom_img：评论的图片
     * classroom_id：课程ID
     * comment_type：1评论课程  2回复评论
     * comment_id：评论的ID  当comment_type为2时，传此值
     */
    public function createComment(){
        $params = input('param.');
        if($params['user_id'] == 0){
            return $this->apiError(4007);
        }
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $data['comment_content'] = trim($params['content'],' ');//评论内容
        if(empty($data['comment_content'])){
            return $this->apiError(4006);
        }
        if($params['comment_type'] == 1){//评论课程
            $data['parent_id'] = 0;//评论的父级ID
        }else{//回复评论
            $data['parent_id'] = $params['comment_id'];//回复的评论ID
        }
        $data['comment_type'] = $params['comment_type'];//回复分类
        $data['classroom_id'] = $params['classroom_id'];//课程ID
        $data['comment_user'] = $params['user_id'];
        $data['comment_img'] = trim($params['comment_img'], ',');//评论图片
        $data['create_time'] = date('Y-m-d H:i:m');
        $classroomCommentModel = new ClassroomCommentModel();
        $res = $classroomCommentModel->createComment($data);
        if(!$res){
            return $this->apiError('K100');
        }else{
            $classroomModel = new ClassroomModel();
            $classroomModel->commentSort(1, $params['classroom_id']);
            return $this->apiSuccess();
        }
    }
    
    /**
     * 删除评论
     * comment_id：被删除的评论或回复ID
     * classroom_id：被删除评论/回复的课程ID
     * type：被删除的是评论还回复   1评论   2回复
     */
    public function delComment(){
        $params = input('param.');
        if($params['user_id'] == 0){
            return $this->apiError(4007);
        }
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        
        $classroomCommentModel = new ClassroomCommentModel();
        
        $user_id = $classroomCommentModel->getUserIDByCommentID($params['comment_id']);
        if($user_id != $params['user_id']){//如果发布评论的用户ID和当前用户ID不一样，则不允许删除
            return $this->apiError('E134');
        }
        
        $ids = $classroomCommentModel->getReplyByComment($params['comment_id']);//根据评论ID获取该评论下所有回复ID
//        $classroom_id = $classroomCommentModel->getClassroomID($params['comment_id']);
        
        if($params['type'] == 1){//删除评论
            //1删除点赞表中该评论的所有点赞记录 2排序字段减对应数量 3删除评论表中的记录
            if(empty($ids)){//评论下无回复
                $this->doDelComment(7, $params, 1);
            }else{
                //删除点赞表中该评论及该评论下所有回复
                Db::table('up_dz')
                    ->where(function ($query) use($params){
                        $query->where('data_id', $params['comment_id'])->where('type', 7);
                    })
                    ->whereOr(function ($query1) use($ids){
                        $query1->where('data_id', 'IN', $ids)->where('type', 8);
                    })
                    ->delete();
                $num = count($ids) + 1;
                $this->doDel($params, $num, $ids);
            }
        }else{//删除回复
            $this->doDelComment(8, $params, 1);
        }
        return $this->apiSuccess();
    }
    
    /**
     * 点赞/取消点赞
     * type：点赞类型     1点赞评论    2点赞回复
     * comment_id：点赞的评论/回复ID
     * like：是否点赞   1已点赞，点击取消点赞     2未点赞，点击点赞
     */
    public function likeComment(){
        $params = input('param.');
        if($params['user_id'] == 0){
            return $this->apiError(4007);
        }
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        if($params['type'] == 1){//点赞评论
            $like = $this->doLike(7, $params);
        }else{//点赞回复
            $like = $this->doLike(8, $params);
        }
        return $this->apiSuccess(['like'=>$like]);
    }
    
    /**
     * 我的收藏/取消收藏
     * collect：收藏状态  1已收藏，点击取消收藏   2未收藏，点击收藏
     * classroom_id：课程ID
     * catalogue_id：章节ID
     */
    public function myCollect(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
        $classroomModel = new ClassroomModel();
        $myClassroomModel = new MyClassroomModel();
        $result = $myClassroomModel->ifCollection($params['classroom_id'], $params['user_id']);
        if($result){//已收藏的，点击取消收藏
            $resD = $myClassroomModel->delCollect($params['classroom_id'], $params['user_id']);
            if(!$resD){//删除记录失败
                return $this->apiError(4005);
            }
            $classroomModel->collectSort(2, $params['classroom_id']);//排序字段减1
            $collect = 2;
        }else{//未收藏，点击添加收藏
            $data = $this->playProgress($params);
            $resA = $myClassroomModel->addCollect($data);
            if(!$resA){//添加收藏失败
                return $this->apiError(4005);
            }
            $classroomModel->collectSort(1, $params['classroom_id']);//排序字段加1
            $collect = 1;
        }
        return $this->apiSuccess(['collect'=>$collect]);
    }
    
    /**
     * 对点赞/取消点赞的操作
     * @param $type 类型  7点赞评论   8点赞回复
     * @param $params  前端传递的参数
     * @return int|void
     */
    protected function doLike($type, $params){
        $classroomCommentModel = new ClassroomCommentModel();
        $data = [
            'user_id' => $params['user_id'],
            'type' => $type,
            'data_id' => $params['comment_id']
        ];
        if($params['like'] == 1){//已点赞，点击取消点赞
            $res = Db::table('up_dz')
                ->where('data_id', $params['comment_id'])
                ->where('user_id', $params['user_id'])
                ->delete();
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(2, $params['comment_id']);//点赞量减1
            $like = 2;//未点赞
        }else{//未点赞，点击点赞
            //将数据插入点赞表
            $res = Db::table('up_dz')->insert($data);
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(1, $params['comment_id']);//点赞量加1
            
            $like = 1;//已点赞
        }
        return $like;
    }
    
    /**
     * 1删除点赞表中该评论的所有点赞记录 2排序字段减对应数量 3删除评论表中的记录
     * @param $type  删除的收藏类型  7评论  8回复
     * @param $params 前度传递的参数
     * @param $num  排序字段减少的数组
     */
    protected function doDelComment($type, $params, $num){
        //删除点赞表中该评论
        Db::table('up_dz')
            ->where('data_id', $params['comment_id'])
            ->where('type', $type)
            ->delete();
        $this->doDel($params, $num);
    }
    
    /**
     * 删除评论时 排序字段减少相应数值，删除该条评论/回复
     * @param $params  前端传递的参数
     * @param $num  被删除的数字
     * @param string $ids  评论下所有回复ID
     */
    protected function doDel($params, $num, $ids = ''){
        $classroomCommentModel = new ClassroomCommentModel();
        $classroomModel = new ClassroomModel();
        $classroomModel->commentSort(2, $params['classroom_id'], $num);//排序字段减$num
        $classroomCommentModel->delComment($params['comment_id'], $ids);//删除该条评论
    }
    
    /**
     * 更新收藏记录
     * classroom_id：课程ID
     * catalogue_id：目录ID
     * 用户已经收藏了该课程，点击目录列表，更换目录时调用
     */
    public function updateCollect(){
        $params = input('param.');
        $myClassroomModel = new MyClassroomModel();
        $data = $this->playProgress($params);
        $field = 'id, catalogue_id';
        $myCollect = $myClassroomModel->ifCollection($params['classroom_id'], $params['user_id'], $field);
        $myClassroomModel->updateCollect($myCollect['id'], $data);
        return $this->apiSuccess();
    }
    
    /**
     * 历史   用户进入课程&用户点击目录时调用
     * classroom_id：课程ID
     * catalogue_id：目录ID  首次加载时，此值传空   默认此课程的第一章节
     */
    public function history(){
        $params = input('param.');
        $data = $this->playProgress($params);
        $classroomHistoryModel = new ClassroomHistoryModel();
        $field = 'history_id, catalogue_id';
        $historyInfo = $classroomHistoryModel->getHistoryInfo($params['user_id'], $params['classroom_id'], $field);
        if(!$historyInfo){
            $classroomHistoryModel->createHistory($data);//没有观看历史，先添加记录
        }else{
            $classroomHistoryModel->updateHistory($historyInfo['history_id'], $data);
        }
        return $this->apiSuccess();
    }
    
    /**
     * 观看进度
     * @param $params  前端传递的数据
     * @return array
     */
    protected function playProgress($params){
        $data = [
            'user_id' => $params['user_id'],//用户ID
            'classroom_id' => $params['classroom_id'],//课程ID
            'classroom_num' => 0,//该课程下所有章节数
            'catalogue_id' => 0,//目录ID
            'catalogue_num' => 0,//用户点击的章节在章节目录中的位置，第几章节
            'classroom_progress' => 0,//播放进度
            'create_time' => date('Y-m-d H:i:s')//观看时间
        ];
        $data['classroom_num'] = count($this->getCatalogueIDS($params['classroom_id']));
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        if($params['catalogue_id'] == ''){//首次进入页面时，默认显示第一节
            $catalogue = $classroomCatalogueModel->getUrl($params['classroom_id'])->toArray();
            $data['catalogue_id'] = $catalogue['catalogue_id'];
        }else{
            $data['catalogue_id'] = $params['catalogue_id'];
        }
        $data['catalogue_num'] = array_search($data['catalogue_id'], $this->getCatalogueIDS($params['classroom_id'])) + 1;
        if($data['classroom_num'] == 0){
            $data['classroom_progress'] = 0 . "%";
        }else{
            $data['classroom_progress'] = number_format($data['catalogue_num']/$data['classroom_num'], 4) * 100 . "%";
        }
        return $data;
    }
    
    /**
     * 根据课程ID ，获取该课程下所有目录的ID
     * @param $classroom_id 课程ID
     * @return array
     */
    protected function getCatalogueIDS($classroom_id){
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        $ids = $classroomCatalogueModel->catalogueIDList($classroom_id);
        return $ids;
    }
    
}